﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Autodesk.Revit.DB;
using YArchitech.Revit;

namespace YJKMenuAssist.Utility
{
	public class ShortcutsFile
	{
		public static string GetShortcuts(CommandInfos commandInfos, XElement rootNode, string tableName)
		{
			string result = "";
			string strCmdId = commandInfos.CmdId;
			if (commandInfos.CmdId == string.Empty)
			{
				strCmdId = string.Concat(new string[]
				{
					"CustomCtrl_%CustomCtrl_%",
					tableName,
					"%",
					commandInfos.PanelName,
					"%",
					commandInfos.CmdName
				});
				commandInfos.CmdId = strCmdId;
			}
			try
			{
				foreach (XElement xelement in from target in rootNode.Descendants("ShortcutItem")
				where target.Attribute("CommandId").Value == strCmdId
				select target)
				{
					result = xelement.Attribute("Shortcuts").Value;
				}
			}
			catch
			{
			}
			return result;
		}

		public static void SetOneKeyboardShortcuts(Autodesk.Revit.DB.Document doc, CommandInfos commandInfos, string tableName, XElement rootNode)
		{
			string strCmdId = commandInfos.CmdId;
			if (commandInfos.CmdId == string.Empty || commandInfos.CmdId == null)
			{
				strCmdId = string.Concat(new string[]
				{
					"CustomCtrl_%CustomCtrl_%",
					tableName,
					"%",
					commandInfos.PanelName,
					"%",
					commandInfos.CmdName
				});
				commandInfos.CmdId = strCmdId;
			}
			IEnumerable<XElement> enumerable = from target in rootNode.Descendants("ShortcutItem")
			where target.Attribute("CommandId").Value == strCmdId
			select target;
			try
			{
				foreach (XElement xelement in enumerable)
				{
					if (commandInfos.KeyBoardName != string.Empty && commandInfos.KeyBoardName != null)
					{
						xelement.SetAttributeValue("Shortcuts", commandInfos.KeyBoardName);
					}
					else
					{
						try
						{
							xelement.Attribute("Shortcuts").Remove();
						}
						catch
						{
						}
					}
				}
			}
			catch
			{
			}
		}

		public static string GetKeyboardShortcutsPath(Autodesk.Revit.DB.Document doc)
		{
			string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
			string versionNumber = RevitVersion.GetVersionNumber(doc);
			return folderPath + "\\Autodesk\\Revit\\Autodesk Revit " + versionNumber + "\\KeyboardShortcuts.xml";
		}
	}
}
